# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: conftest.py
# Time: 14:15


import pytest
from appium import webdriver

from bin.common.element import ElementActions
from bin.config.initialize import InitializeDevice
from bin.util.log_util import LogGing

dev = InitializeDevice()

app = dev.obtain_app_information()

current_device = dev.current_device



@pytest.fixture(scope="package")
def log():
    global log
    log = LogGing().logger()
    return log


@pytest.fixture("package")
def deiverenv(log):
    try:
        capabilities = {
            'platformName': current_device.get("platformName"),
            'platformVersion': current_device.get("platformVersion"),
            'deviceName': current_device.get("deviceName"),
            'udid': current_device.get("deviceName"),
            'systemPort': current_device.get('systemPort'),
            'app': app.get("app_path"),
            'clearSystemFiles': True,
            'appActivity': app.get("activity"),
            'appPackage': app.get("apppackage"),
            'automationName': 'UIAutomator2',
            'noSign': True,
            'recreateChromeDriverSessions': True,
            "unicodeKeyboard": True,
            "noReset": True,
            "fullReset": False,
            "newCommandTimeout": 300
        }
        host = current_device.get("appiumserver")
        log.info("当前执行的APPIUM相关配置为：" + str(capabilities))
        driver = webdriver.Remote(host, capabilities)
        driver.implicitly_wait(2)
        return driver
    except Exception as e:
        log.warning("driver启动失败，失败原因：{}".format(e))
        raise


# 初始化ElementActions类的对象，在package的领域只会执行一次，并且通过yield实现package执行结束前的数据清理工作
@pytest.fixture(scope="package")
def action(deiverenv):
    element_action = ElementActions(deiverenv, log)
    yield element_action  # 返回并且挂载ElementActions的实例，在对应作用域结束前，执行driver.quit()
    element_action.driver.quit()


# 用例执行前后：加入日志说明、结束前的截图输出到报告上
@pytest.fixture(autouse=True)
def caserun(action):
    log.info("————————————————————————执行用例 ----------——————————————")
    yield
    action.sleep(1).get_screenshot("用例结束前的截图")
    log.info("————————————————————————该用例执行结束 ----------——————————————")
